/**
 * Copyright 2011 Mathieu Magnaudet
 * 
 * This program is free software: you can redistribute it and/or modify
 * it under the terms of the GNU Lesser General Public License as published by
 * the Free Software Foundation, either version 3 of the License, or
 * (at your option) any later version.
 *
 *  This program is distributed in the hope that it will be useful,
 *  but WITHOUT ANY WARRANTY; without even the implied warranty of
 *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 *  GNU Lesser General Public License for more details.
 *
 *  You should have received a copy of the GNU Lesser General Public License
 *  along with this program.  If not, see <http://www.gnu.org/licenses/>.
 */

package edu.enac.geoapp.gui;

import java.awt.Color;
import java.awt.Container;
import java.awt.GridBagConstraints;
import java.awt.GridBagLayout;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.util.Properties;

import javax.swing.JFrame;
import javax.swing.JPanel;

import org.geotools.swing.JMapPane;

import edu.enac.fileloader.exception.FileLoaderException;
import edu.enac.fileloader.ivylistener.IvyAgent;
import edu.enac.fileloader.service.FTPFileLoader;
import edu.enac.fileloader.service.Host;
import edu.enac.fileloader.service.UserAccount;
import edu.enac.fileloader.util.FileNameParser;
import edu.enac.fileloader.util.Observable;
import edu.enac.fileloader.util.Observer;

import edu.enac.geoapp.gui.component.MapComponent;
import edu.enac.geoapp.gui.component.NewFileInternalFrame;
import edu.enac.geoapp.gui.component.OrientationSelector;
import edu.enac.geoapp.gui.component.RangeSelectorContainer;
import edu.enac.geoapp.gui.component.ViewSelector;
import edu.enac.geoapp.gui.custom.component.ImagePanel;
import edu.enac.geoapp.model.Format;
import edu.enac.geoapp.model.Orientation;
import edu.enac.geoapp.model.Product;
import edu.enac.geoapp.model.View;
import edu.enac.geoapp.services.FileStore;
import edu.enac.geoapp.services.ViewController;
import fr.dgac.ivy.IvyException;

/**
 * Fenêtre principale
 * 
 * @author mathieu
 * 
 */
public class GeoAppMainWindow implements Observer {

	private static FileNameParser parser;
	private static FTPFileLoader loader;
	private static MapComponent mapComponent;
	private static JMapPane pane;
	private static OrientationSelector orientationSelector;
	private static ViewSelector viewSelector;
	private static RangeSelectorContainer range;
	private static JFrame frame;
	public GeoAppMainWindow() throws FileNotFoundException, IOException {
		Properties prop = new Properties();
		prop.load(new FileInputStream("conf/network_parameters.properties"));
		UserAccount account = new UserAccount(prop.getProperty("username"),
				prop.getProperty("pwd"));
		Host host = new Host(prop.getProperty("host"), prop.getProperty("port"));
		parser = new FileNameParser();
		loader = new FTPFileLoader(host, account, prop.getProperty("dest"));
		

		IvyAgent agent = IvyAgent.getInstance();
		try {
			agent.start();
			agent.addObserver(this);
		} catch (IvyException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (FileLoaderException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}

		// initialise les composants principaux
		mapComponent = new MapComponent();
		pane = mapComponent.getMapPane();
		orientationSelector = new OrientationSelector(Orientation.NORTH);
		viewSelector = new ViewSelector();
		viewSelector.addPane(pane);
		range = new RangeSelectorContainer();

		// ajoute un écouteurs aux différents composants
		ViewController manager = new ViewController(View.NAV,
				Orientation.NORTH, 0, mapComponent, viewSelector);
		agent.addObserver(manager);
		orientationSelector.addOrientationListener(manager);
		viewSelector.addViewListener(manager);
		viewSelector.addDataScrollListener(manager);
		range.addRangeListener(manager);

		javax.swing.SwingUtilities.invokeLater(new Runnable() {
			public void run() {
				try {
				createAndShowGUI();
				} catch (Exception e) {
					
				}
			}
		});

	}

	private void createAndShowGUI() {

		final ImagePanel vpanel = new ImagePanel("images/vpanel.png");
		final ImagePanel hpanel = new ImagePanel("images/hpanel.png");
		final JPanel centerPanel = new JPanel();
		centerPanel.setLayout(null);
		final JPanel bottomPanel = new JPanel();
		bottomPanel.setBackground(Color.WHITE);

		frame = new JFrame("Capitole Meteo App");

		frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
		frame.setResizable(false);
		frame.setBackground(Color.BLACK);
		Container container = frame.getContentPane();
		container.setLayout(new GridBagLayout());

		GridBagConstraints c = new GridBagConstraints();
		c.gridwidth = 2;
		c.gridx = 0;
		c.gridy = 0;
		c.fill = GridBagConstraints.NONE;
		container.add(hpanel, c);

		c = new GridBagConstraints();
		c.gridx = 0;
		c.gridy = 1;
		c.fill = GridBagConstraints.BOTH;
		c.weightx = 100;
		c.weighty = 95;
		container.add(pane, c);

		c = new GridBagConstraints();
		c.gridx = 0;
		c.gridy = 2;
		c.fill = GridBagConstraints.BOTH;
		c.weighty = 5;
		container.add(mapComponent.getInfo(), c);

		c = new GridBagConstraints();
		c.gridx = 1;
		c.gridy = 1;
		c.gridheight = 2;
		c.fill = GridBagConstraints.NONE;
		container.add(vpanel, c);

		hpanel.add(orientationSelector);
		hpanel.add(range);

		vpanel.add(viewSelector);
		frame.pack();
		frame.setVisible(true);
	}

	/**
	 * @param args
	 * @throws IOException
	 * @throws FileNotFoundException
	 */
	public static void main(String[] args) throws FileNotFoundException,
			IOException {
		new GeoAppMainWindow();
	}

	@Override
	public void update(Observable o, Object arg) {
		if(o instanceof IvyAgent) {
			Product product = null;
			String filename = null;
			Format format = null;
			try {
				parser.parse((String)arg);
				String directory = parser.getDir();
				filename = parser.getFilename();
				 format = parser.getFormat();
				product = parser.getProduct();
				
				loader.getFile(directory, filename, format);
			} catch (FileLoaderException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
			
			if(product != null) {
				updateFileStore(loader.getDestinationDirectory(), filename, product );
				alertNewIncomingFile(product);
			}
			
		}
	}

	private void updateFileStore(String destinationDirectory, String filename,
			Product product) {
		String path;
		FileStore store = FileStore.getInstance();
		if(destinationDirectory.endsWith(File.separator))
			path = destinationDirectory + filename;
		else
			path = destinationDirectory + File.separator + filename;
		System.out.println("nouvelles données: " + path);
		switch (product) {
		case METAR:
			store.setPathToMetar(path);
			break;
		case RADAR:
			store.setPathToRadar(path);
			break;
		case SAT_IR:
			store.setPathToSatIr(path);
			break;
		case SAT_VIS:
			store.setPathToSatVis(path);
			break;
		case SIGMET:
			break;
		case TAF:
			store.setPathToTaf(path);
			break;
		case TEMPERATURE:
			store.setPathToTempFile(path);
			break;
		case TEMSI_EUROPE:
			store.setPathToTemsi(path);
			break;
		case TEMSI_FRANCE:
			store.setPathToTemsi(path);
			break;
		case VENT:
			store.setPathToWindFile(path);
			break;
		case WIMS_CAT:
			store.setPathToMtoObjectsFile(path);
			break;
		case WIMS_CB:
			store.setPathToMtoObjectsFile(path);
			break;
		case WIMS_ICE:
			store.setPathToMtoObjectsFile(path);
			break;
		default:
			break;
		}
	}

	private void alertNewIncomingFile(Product product) {
		String msg = "Nouvelles données disponibles de type: " + product;
		System.out.println(msg);
		NewFileInternalFrame alert = new NewFileInternalFrame(msg);
		mapComponent.getMapPane().add(alert);
		alert.setVisible(true);
		try {
			alert.setSelected(true);
		} catch (java.beans.PropertyVetoException e) {

		}
	}
}
